from flask import Flask, request, jsonify, send_from_directory
from mysql.connector import connect, Error
from flask_cors import CORS
import re
import logging
from datetime import datetime

app = Flask(__name__, static_folder='static', static_url_path='')

# 使用 CORS 并允许所有来源
CORS(app, resources={r"/*": {"origins": "*"}})

# 配置日志记录
logging.basicConfig(level=logging.DEBUG)
#
# MySQL 配置
db_config = {
    'user': 'login_user',
    'password': '216474',
    'host': '82.156.19.25',
    'database': 'login_user'
}

@app.route('/')
def serve_index():
    return send_from_directory(app.static_folder, 'index.html')

@app.route('/register', methods=['POST'])
def register():
    data = request.json
    username = data.get('username')
    password = data.get('password')

    if not username or not password:
        return jsonify({'message': '用户名和密码不能为空!'}), 400

    if not re.match(r'^[a-zA-Z0-9]+$', username):
        return jsonify({'message': '必须使用字母和数字!'}), 400

    try:
        connection = connect(**db_config)
        cursor = connection.cursor(dictionary=True)
        cursor.execute('SELECT * FROM users WHERE username = %s', (username,))
        account = cursor.fetchone()
        
        if account:
            return jsonify({'message': '账户已经存在!'}), 400
        else:
            cursor.execute('INSERT INTO users (username, password) VALUES (%s, %s)', (username, password))
            connection.commit()
            return jsonify({'message': '恭喜你,成功注册!'}), 201
    except Error as e:
        logging.error(f"Database error: {e}")
        return jsonify({'message': '数据库错误'}), 500
    finally:
        if 'cursor' in locals():
            cursor.close()
        if 'connection' in locals():
            connection.close()

@app.route('/login', methods=['POST'])
def login():
    data = request.json
    username = data.get('username', '').strip()
    password = data.get('password', '').strip()
    
    if not username or not password:
        return jsonify({'success': False, 'message': '用户名和密码不能为空!'}), 400

    try:
        connection = connect(**db_config)
        cursor = connection.cursor(dictionary=True)
        query = 'SELECT * FROM users WHERE username = %s'
        cursor.execute(query, (username,))
        account = cursor.fetchone()

        if account and account.get('password') == password:
            return jsonify({
                'success': True, 
                'message': '登录成功!!!', 
                'username': account['username'],
                'user_id': account.get('id')  # 确保字段存在
            }), 200
        else:
            return jsonify({'success': False, 'message': '无效的用户名/密码!!'}), 401
    except Error as e:
        logging.error(f"Database error: {e}")
        return jsonify({'success': False, 'message': '数据库错误'}), 500
    finally:
        if 'cursor' in locals():
            cursor.close()
        if 'connection' in locals():
            connection.close()

@app.route('/get_sales_data', methods=['GET'])
def get_sales_data():
    user_id = request.args.get('user_id')
    if not user_id:
        return jsonify({'success': False, 'message': '用户的账号不存在'}), 400
    
    try:
        logging.debug(f'Getting sales data for user_id: {user_id}')
        connection = connect(**db_config)
        cursor = connection.cursor(dictionary=True)
        cursor.execute('SELECT * FROM sales WHERE user_id = %s', (user_id,))
        sales_data = cursor.fetchall()
        for sale in sales_data:
            sale['date'] = sale['date'].strftime('%Y-%m-%d')
        return jsonify({'success': True, 'sales': sales_data}), 200
    except Error as e:
        logging.error(f"Database error: {e}")
        return jsonify({'success': False, 'message': '数据库错误'}), 500
    finally:
        if 'cursor' in locals():
            cursor.close()
        if 'connection' in locals():
            connection.close()

@app.route('/add_sales_data', methods=['POST'])
def add_sales_data():
    data = request.json
    user_id = data.get('user_id')
    if not user_id:
        return jsonify({'success': False, 'message': '用户的账号不存在'}), 400
    
    logging.debug(f'Adding sales data for user_id: {user_id}')
    product = data.get('product')
    date = data.get('date')
    quantity = data.get('quantity')
    price = data.get('price')
    total = data.get('total')
    
    if not all([product, date, quantity, price, total]):
        return jsonify({'success': False, 'message': '所有字段都必须填写'}), 400

    try:
        connection = connect(**db_config)
        cursor = connection.cursor()
        cursor.execute('INSERT INTO sales (user_id, product, date, quantity, price, total) VALUES (%s, %s, %s, %s, %s, %s)',
                       (user_id, product, date, quantity, price, total))
        connection.commit()
        return jsonify({'success': True}), 201
    except Error as e:
        logging.error(f"Database error: {e}")
        return jsonify({'success': False, 'message': '数据库错误'}), 500
    finally:
        if 'cursor' in locals():
            cursor.close()
        if 'connection' in locals():
            connection.close()

@app.route('/update_sales_data', methods=['PUT'])
def update_sales_data():
    data = request.json
    user_id = data.get('user_id')
    if not user_id:
        return jsonify({'success': False, 'message': '请登录再进行操作'}), 401
    
    logging.debug(f'Updating sales data for user_id: {user_id}')
    sale_id = data.get('id')
    product = data.get('product')
    date = data.get('date')
    quantity = data.get('quantity')
    price = data.get('price')
    total = data.get('total')
    
    if not all([sale_id, product, date, quantity, price, total]):
        return jsonify({'success': False, 'message': '所有字段都必须填写'}), 400

    try:
        connection = connect(**db_config)
        cursor = connection.cursor()
        cursor.execute('UPDATE sales SET product = %s, date = %s, quantity = %s, price = %s, total = %s WHERE id = %s AND user_id = %s',
                       (product, date, quantity, price, total, sale_id, user_id))
        connection.commit()
        return jsonify({'success': True}), 200
    except Error as e:
        logging.error(f"Database error: {e}")
        return jsonify({'success': False, 'message': '数据库错误'}), 500
    finally:
        if 'cursor' in locals():
            cursor.close()
        if 'connection' in locals():
            connection.close()

@app.route('/delete_sales_data', methods=['DELETE'])
def delete_sales_data():
    data = request.json
    user_id = data.get('user_id')
    if not user_id:
        return jsonify({'success': False, 'message': '请登录后再进行删除操作'}), 401
    
    logging.debug(f'Deleting sales data for user_id: {user_id}')
    sale_id = data.get('id')
    
    if not sale_id:
        return jsonify({'success': False, 'message': '销售记录 ID 不能为空'}), 400

    try:
        connection = connect(**db_config)
        cursor = connection.cursor()
        cursor.execute('DELETE FROM sales WHERE id = %s AND user_id = %s', (sale_id, user_id))
        connection.commit()
        return jsonify({'success': True}), 200
    except Error as e:
        logging.error(f"Database error: {e}")
        return jsonify({'success': False, 'message': '数据库错误'}), 500
    finally:
        if 'cursor' in locals():
            cursor.close()
        if 'connection' in locals():
            connection.close()

@app.route('/user', methods=['GET'])
def get_user_info():
    username = request.args.get('username')
    if not username:
        return jsonify({'success': False, 'message': '请提供用户名'}), 400
    
    try:
        connection = connect(**db_config)
        cursor = connection.cursor(dictionary=True)
        cursor.execute('SELECT username FROM users WHERE username = %s', (username,))
        user = cursor.fetchone()
        if user:
            return jsonify({'success': True, 'username': user['username']}), 200
        else:
            return jsonify({'success': False, 'message': '用户不存在'}), 404
    except Error as e:
        logging.error(f"Database error: {e}")
        return jsonify({'success': False, 'message': '数据库错误'}), 500
    finally:
        if 'cursor' in locals():
            cursor.close()
        if 'connection' in locals():
            connection.close()

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)
